import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order, OrderStatus } from '../entity/order.entity';
import { OrderItem } from '../entity/order-item.entity';
import { ProductSku } from '../entity/product-sku.entity';
import { Shipping } from '../entity/shipping.entity';
import { Payment } from '../entity/payment.entity';
import { ShippingStatus } from '../entity/shipping.entity'
import { OrderNumberService } from '../order-number/order-number.service'
import { FormatService } from '../format/format.service';
@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private orderRepository: Repository<Order>,
    @InjectRepository(OrderItem)
    private orderItemRepository: Repository<OrderItem>,
    @InjectRepository(ProductSku)
    private skuRepository: Repository<ProductSku>,
    @InjectRepository(Shipping)
    private shippingRepository: Repository<Shipping>,
    @InjectRepository(Payment)
    private paymentRepository: Repository<Payment>,
    private generateOrderNo:OrderNumberService,
    private formatService:FormatService,
  ) {}

  async create(createData: {
    userId: number;
    items: {
      skuId: number;
      quantity: number;
    }[];
    shippingAddress: {
      name: string;
      phone: string;
      province: string;
      city: string;
      district: string;
      address: string;
    };
    remark?: string;
  }) {
    // console.log(createData)
    // 检查库存并计算总金
    let totalAmount = 0;
    const orderItems = [];

    for (const item of createData.items) {
      const sku = await this.skuRepository.findOne({
        where: { id: item.skuId },
        relations: ['product'],
      });

      if (!sku) {
        throw new NotFoundException(`SKU ${item.skuId} 不存在`);
      }

      if (sku.stock < item.quantity) {
        throw new BadRequestException(`SKU ${sku.stock} 库存不足`);
      }

      const itemTotal = sku.price * item.quantity;
      totalAmount += itemTotal;
      const items = await  this.orderItemRepository.create({
          sku,
          productSnapshot: sku.product,
          quantity: item.quantity,
          unitPrice: sku.price,
          totalPrice: itemTotal,
        //   attributes: sku.attributes,
        //   image: sku.image,
      })

      orderItems.push(
       items,
      );
    }

    // 创建订单
    const date = this.formatService.dateFormate(new Date(),'YYYY-MM-DD HH:mm:ss.SSSSSS')
    const thatOder = {
      user_id: createData.userId,
      orderNo:this.generateOrderNo.generateOrderNumber('ORD'),
      status: OrderStatus.PENDING,
      totalAmount,
    //   finalAmount: totalAmount,
      shippingAddress: createData.shippingAddress,
      remark: createData.remark,
      createdAt:date,
      updatedAt:date,

    }
    const order = await this.orderRepository.create(thatOder);
     console.log('items--oooo:',order)
    await this.orderRepository.save(order);

    // 保存订单
    for (const item of orderItems) {
      item.order = order;
      console.log('order-----:',item)
      await this.orderItemRepository.save(item);
    }

    console.log('orderItems--end:',order)

    let one = await this.findOne(order.id);
    console.log('输出one：',one)
    return one;
  }

  async findAll(query: {
    user_id?: number;
    page?: number;
    limit?: number;
    status?: OrderStatus;
  }) {
    const { user_id:userId, page = 1, limit = 10, status } = query;
    const skip = (page - 1) * limit;

    const qb = this.orderRepository
      .createQueryBuilder('order')
      .leftJoinAndSelect('order.items', 'items')
      .leftJoinAndSelect('items.sku', 'sku')
      .leftJoinAndSelect('items.product', 'product')
      .where('1=1');

    if (userId) {
      qb.andWhere('order.user_id = :user_id', { userId });
    }

    if (status) {
      qb.andWhere('order.status = :status', { status });
    }

    const [orders, total] = await qb
      .orderBy('order.createdAt', 'DESC')
      .skip(skip)
      .take(limit)
      .getManyAndCount();

    return {
      items: orders,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async findOne(id: number) {
    console.log('order:findOneId:',id)
    const order = await this.orderRepository.findOne({
      where: { id },
      // relations: ['items',
      //   // 'items.sku', 'items.product',

      //   // 'paymentMethod',
      //   // 'shippingsAddress'
      // ],
      // relations:['user_id']
    });

    console.log('order:findOne:',order)

    if (!order) {
      throw new NotFoundException('订单不存?');
    }

    return order;
  }

  async updateStatus(id: number, status: OrderStatus) {
    const order = await this.findOne(id);
    order.status = status;
    await this.orderRepository.save(order);
    return this.findOne(id);
  }

  async createShipping(id: number, shippingData: {
    carrier: string;
    trackingNumber: string;
  }) {
    const order = await this.findOne(id);
    if (order.status !== OrderStatus.PAID) {
      throw new BadRequestException('订单状态不正确');
    }

    const shipping = this.shippingRepository.create({
      order,
      //carrier: shippingData.carrier,
      trackingNumber: shippingData.trackingNumber,
      shippingAddress: order.shippingAddress,
      status: ShippingStatus.SHIPPED,
    });

    await this.shippingRepository.save(shipping);
    await this.updateStatus(id, OrderStatus.SHIPPED);

    return this.findOne(id);
  }

  async updateShippingStatus(id: number, shippingId: number, status: ShippingStatus) {
    const order = await this.findOne(id);
    const shipping = await this.shippingRepository.findOne({
      where: { id: shippingId, order: { id } },
    });

    if (!shipping) {
      throw new NotFoundException('发货记录不存?');
    }

    shipping.status = status;
    await this.shippingRepository.save(shipping);

    if (status === 'DELIVERED') {
      await this.updateStatus(id, OrderStatus.COMPLETED);
    }

    return this.findOne(id);
  }

  // private generateOrderNo(): string {
  //   const date = new Date();
  //   const year = date.getFullYear();
  //   const month = String(date.getMonth() + 1).padStart(2, '0');
  //   const day = String(date.getDate()).padStart(2, '0');
  //   const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
  //   return `${year}${month}${day}${random}`;
  // }
}
